package cn.xiaolang.thread.concurrent;

/**
 * 等待唤醒机制：
 * 解决了多生产多消费的问题（重复商品，死锁问题）
 * 存在一个弊端：程序的执行效率过低。
 * 过低的原因：在唤醒时全唤醒全部的等待线程，并不能唤醒对方线程
 *
 * @author DeanKano
 */
public class ProduceConsumerWaitNotifyAll {

    public static void main(String[] args) {
        ShareResource resource = new ShareResource();
        new Thread(new Producer(resource), "P1").start();
        new Thread(new Producer(resource), "P2").start();
        new Thread(new Producer(resource), "P3").start();
        new Thread(new Consumer(resource), "C1").start();
        new Thread(new Consumer(resource), "C2").start();
    }

    static class Producer implements Runnable {

        private ShareResource resource;

        Producer(ShareResource resource) {
            super();
            this.resource = resource;
        }

        @Override
        public void run() {
            int num = 1;
            while (true) {
                resource.putSyncWhileWaitNotifyAll(Thread.currentThread().getName() + num);
                num++;
            }
        }
    }

    static class Consumer implements Runnable {
        private ShareResource resource;

        Consumer(ShareResource resource) {
            this.resource = resource;
        }

        @Override
        public void run() {
            while (true) {
                resource.gainSyncWhileWaitNotifyAll();
            }
        }
    }
}





